require('whatwg-fetch');
let comDriver = require('@/common/driver');

async function request(url = '', data = {}, type = 'POST', method = 'fetch', headers = {}, credentials = false) {
    type = type.toUpperCase();
    if (type == 'GET') {
        let dataStr = ''; //数据拼接字符串
        Object.keys(data).forEach(key => {
            dataStr += key + '=' + data[key] + '&';
        })

        if (dataStr !== '') {
            dataStr = dataStr.substr(0, dataStr.lastIndexOf('&'));
            url = url + '?' + dataStr;
        }
    }
    if (fetch && method == 'fetch') {
        let requestConfig = {
            method: type,
        };

        if (credentials) requestConfig.credentials = "include";

        if (type == 'POST') {
            if (headers) requestConfig.headers = headers;

            Object.defineProperty(requestConfig, 'body', {
                value: JSON.stringify(data)
            })
        } else if (type == 'UPLOAD') {
            requestConfig.method = 'POST';
            requestConfig.mode = 'no-cors';
            requestConfig.headers = {};
            requestConfig.body = data;
        }

        try {
            const response = await fetch(url, requestConfig);
            if (type == 'POST') {
                const responseJson = await response.json();
                return responseJson;
            }else{
                const responseXml = response.text();
                return responseXml;
            }
        } catch (error) {
            throw new Error(error)
        }
    } else {
        return new Promise((resolve, reject) => {
            let requestObj;
            if (window.XMLHttpRequest) {
                requestObj = new XMLHttpRequest();
            } else {
                requestObj = new ActiveXObject;
            }

            let method = '';
            let sendData = '';
            if (type == 'POST') {
                sendData = JSON.stringify(data);
                method = 'POST';
            } else if (type == 'UPLOAD') {
                sendData = data;
                method = 'POST';
            } else if (type == 'GET') {
                sendData = data;
                method = 'GET';
            }

            requestObj.open(method, url, true);
            if (type == 'POST') {
                requestObj.setRequestHeader("Content-type", "application/json");
            }
            requestObj.send(sendData);

            requestObj.onreadystatechange = () => {
                if (type == 'UPLOAD') {
                    if (requestObj.status == 200) {
                        let obj = requestObj.response;
                        if (typeof obj !== 'object') {
                            obj = obj ? JSON.parse(obj) : {};
                        }
                        resolve(obj)
                    } else {
                        reject(requestObj)
                    }
                } else if (type == 'GET') {
                    if (requestObj.readyState == 4) {
                        if (requestObj.status == 200) {
                            let obj = requestObj.response;
                            resolve(obj);
                            return;
                        } else {
                            reject(requestObj)
                            return;
                        }
                    }
                    // carw有时成功会返回 !4
                    // else
                    //     reject(requestObj);
                } else {
                    if (requestObj.readyState == 4) {
                        if (requestObj.status == 200) {
                            let obj = requestObj.response;
                            if (typeof obj !== 'object') {
                                obj = obj ? JSON.parse(obj) : {};
                            }
                            resolve(obj);
                            return;
                        } else {
                            reject(requestObj)
                            return;
                        }
                    }
                }
            }
        })
    }
}

module.exports = async (method, param) => {
    let formatParam = await comDriver.app().core.getBeanClass('server.formatParam');
    let formatResult = await comDriver.app().core.getBeanClass('server.formatResult');
    let data = formatParam(method, param);
    let result = await request(data.url, data.param);
    return formatResult(result);
}
